package com.telecom.cms.dao;

import java.sql.Connection;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DataSourceConnectionFactory;
import com.teradata.db.*;
import com.teradata.tap.system.query.QueryException;
import com.telecom.cms.util.*;

/**
 * @author yueyingnishang
 * 
 */
public class GetConnect {

	
	private final static int poolsize= Integer.parseInt(com.telecom.cms.util.Constant.getStPara("POOLSIZE"));
	private final static int dfpoolsize= Integer.parseInt(com.telecom.cms.util.Constant.getStPara("DFPOOLSIZE"));
	private final static int stdpoolsize= Integer.parseInt(com.telecom.cms.util.Constant.getStPara("STDPOOLSIZE"));

	private static BasicDataSource ds = null;
	private static Connection[] con= new Connection[poolsize];
	private final static int actauth=Constant.CheckAuth();
	/**
	 * @return
	 */
	public static synchronized Connection getConnection() {
		if(actauth<2)
		{
			System.out.println("Only Auth to access CS, no CMS. Get auth first!");
			return null;
		}
		return getConnection(0,0,poolsize-dfpoolsize);
	}
	
	public static synchronized Connection getStdConnection() {
		return  getConnection(0,0,stdpoolsize);
	}
	
	public static synchronized Connection getCsConnection() {
		return  getConnection(1,-dfpoolsize,dfpoolsize);
	}
	
	public static synchronized Connection getConnection(int start,int pos,int width) {
		if(actauth<0)
		{
			System.out.println("No auth to use TCMS. Get auth first!");
			return null;
		}
		
		String serverType = (new Constant()).getPara("SERVERTYPE");
		//String serverType = "TOMCAT";
		int rand=start*poolsize+pos+(int)Math.floor(Math.random()*width);
		
		while(rand>poolsize-1||rand<0)
			rand=start*poolsize+pos+(int)Math.floor(Math.random()*width);
		
		if (con[rand] == null) {
			if (serverType.equalsIgnoreCase("TOMCAT")) {
				if (ds == null) {
					ds = new BasicDataSource();

					ds.setDriverClassName(com.telecom.cms.util.Constant.getStPara("DB_DRIVER"));
					ds.setUrl(com.telecom.cms.util.Constant.getStPara("CONNSTR"));
					ds.setUsername(com.telecom.cms.util.Constant.getStPara("CONNUSER"));
					ds.setPassword(com.telecom.cms.util.Constant.getStPara("CONNPASS"));

					ds.setMaxActive(0); //0 means no limit
					ds.setInitialSize(poolsize+2); //初始化连接数量
					ds.setMaxIdle(0); //0 means no limit
					ds.setMaxWait(1000*1200); //超时回收时间
					System.out.println("OK,We build a datasource pool of size "+poolsize+",and "+dfpoolsize+" are for CS.Good luck!");
				}

				try {
					con[rand]=ds.getConnection();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println(e.toString());
				}
			} 
		}
		return con[rand];
	}

}
